<template>
  <div class="grid_gadget_tempalte"
       style="width:100%;height:100%">
    <Portal to="right-disable"
            style="width:100%;height:100%;"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <el-card shadow="never"
               class="aui-card--fill content-card"
               :style="isHasData?'width:100%;height: 100%;border:0;overflow: visible;':'width:100%;height: 100%;border:0;overflow: hidden;'"
               v-show="queryShow">
        <div style="width:100%;height:100%;overflow: hidden;">
          <div class="cardHeader"
               @mouseenter="mouseenter(true)"
               @mouseleave="mouseenter(false)"
               v-if="(gadgetSetting.report&&gadgetSetting.report.showHeader) && (widgetName&& widgetName.trim().length>0)">
            <GadgetTitle :gadgetSetting="gadgetSetting"
                         :widgetName="widgetName"></GadgetTitle>
            <div>
              <MoreMenu :slicer='slicer'
                        :fitToHeight='fitToHeight'
                        :gadgetId='id'
                        :gadgetType='gadgetInfo.com'
                        @updateQuery="query"
                        :widgetName="widgetName"
                        :businessType="gadgetInfo.businessType"
                        :id="gadgetInfo.id"
                        @showQueryModel="showQueryModel" />
            </div>
          </div>
          <div style="padding: 10px 10px;">
            <!-- <el-button type="primary"
                       size="small"
                       @click="openDialog()">{{$t('new')}}</el-button> -->
            <el-button size="small"
                       v-for="(item,index) in toolbarEventList"
                       :key="index"
                       :type="item.type"
                       :loading="item.loading"
                       :icon="item.icon"
                       :disabled="loading"
                       @click="actionHandler(item)">
              {{item.text}}
            </el-button>
            <el-input v-if="isHasData && gadgetSetting.showSearch"
                      style="width: 200px; float: right"
                      prefix-icon="el-icon-search"
                      placeholder="search"
                      v-model="search">
            </el-input>
          </div>
          <div class="control-section"
               style="margin: 0px 10px 10px 10px;height: calc(100% - 90px)">
            <div class="content-wrapper"
                 style="width:100%;height:100%;"
                 :class="gadgetSetting.report.allowGrouping?'':'showToobar'">
              <BTable :tableData="searchTableData(comDataList)"
                      :columns="comColumns"
                      :header-row-style="{height:'36px'}"
                      :header-cell-style="{height:'36px',padding:0}"
                      :summary-method="getSummaries"
                      :show-summary="comIsShowSummary&&!autoFull"
                      :conditionFormat="conditionFormat"
                      :startIndex="startIndex"
                      :autoFull="autoFull"
                      :endIndex="endIndex"
                      :pageConfig="pageConfig"
                      :stripe="conditionFormat && conditionFormat.length > 0 ?false :true"
                      :gadgetHeight="gadgetHeight"
                      @handleTableExport="handleTableExport"
                      @selection-change="handleSelectionChange"
                      @cell-click="tableCellClick"
                      @sort-change="sortChange"
                      :cell-class-name="tableCellClassName"
                      :gadgetSetting="gadgetSetting"
                      v-if="isHasData">
                      <el-table-column
                      slot="selection"
                      type="selection"
                      v-if="gadgetSetting.showSelection"
                      width="55">
                  </el-table-column>
                  <el-table-column
                    slot="index"
                    type="index"
                    width="50"
                    v-if="gadgetSetting.showLineNumbers"
                    ></el-table-column>
                <el-table-column :show-overflow-tooltip="true"
                                 v-for="column in comColumns"
                                 :slot="column.field"
                                 :key="column.field"
                                 sortable
                                 :sort-method="(a,b) => customSort(a, b, column.field)"
                                 :align="getTextAlign(column.textAlign)"
                                 :prop="column.field"
                                 :min-width="(!column.maxWidth || column.maxWidth === 'auto') ? getColumnWidth(column.field) : column.maxWidth"
                                 :width="column.maxWidth">
                  <template slot="header">
                    <el-tooltip v-if="column.headerTextTooltip"
                                effect="dark"
                                :content="column.headerTextTooltip"
                                placement="right">
                      <span style="white-space: nowrap;">
                        {{column.headerText?column.headerText:column.field}}
                      </span>
                    </el-tooltip>
                    <span style="white-space: nowrap;"
                          v-else>{{column.headerText?column.headerText:column.field}}</span>
                  </template>
                  <template slot-scope="scope">
                    <component :is="`${findTableTemplateName(column.templateName)}`"
                               :dataFrom="'Table'"
                               :curData="scope.row[column.field]"
                               :curRow="scope.row"
                               :rowHeight="gadgetSetting.report.rowHeight"
                                :textAlign="getTextAlign(column.textAlign,'flex')"
                               :column="column"></component>
                  </template>
                </el-table-column>
                <template slot="tableAction">
                  <el-table-column
                      v-if="columnEventList.length > 0"
                      fixed="right"
                      align="center"
                      :min-width="getActionColumnWidth(columnEventList)"
                      :label="$t('custom.component.gadget.operations')">
                    <template slot-scope="scope">
                      <crud-plus-btn @actionHandler="actionHandler"
                                     :scope="scope.row"
                                     :columnEventList="columnEventList"
                                     :formCode="gadgetSetting.report.formList"
                                     >
                      </crud-plus-btn>
                    </template>
                  </el-table-column>
                </template>
              </BTable>
              <Pagination v-if="isHasData&&gadgetSetting.report.allowPaging" @query="query" v-model="pageConfig"></Pagination>
              <div v-if="!isHasData"
                 class="gadget-no-newdata">
                 <el-image @click="query()"
                          :src="noDataImageUrl"
                          fit="fill"></el-image>
              </div>
            </div>
          </div>
        </div>
      </el-card>
      <Lastupdatetime v-if="currentTime"
                      :currentTime="currentTime"
                      :linkedDatasetList="linkedDatasetList"
                      @updateQuery="query()"></Lastupdatetime>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting" />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
    <formviewdialog :formViewData="formViewData"
                    :rowDataItem="rowDataItem"
                    @query="queryItem"
                    ref="formView-dialog"
                    v-if="formViewVisible"></formviewdialog>
    <drillDialog ref="drill-dialog"
                 v-if="drillDialogVisible"></drillDialog>
    <el-dialog title="出库扫码"
               :visible.sync="dialogVisible"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :append-to-body="true"
               @opened="openedOut"
               width="30%"
               :before-close="handleClose">
      <div style="display: flex;justify-content: center;align-items: center;">
        <vue-qr :text="qrcontent.code"
                :size="200"
                :margin="0"
                colorDark="black"
                colorLight="white"></vue-qr><br>
      </div>
      <div style="display: flex;justify-content: center;align-items: center;margin-top:10px;">
        <span>{{qrcontent.text}}</span>
      </div>
      <div style="">
        <h4>扫码框:</h4>
        <el-input id="outboundCode"
                  ref="codeinput"
                  v-model="outboundCode"
                  placeholder="扫描框"
                  @blur="compareCode"
                  style="width:90%;margin-left:10px;"
                  prefix-icon="el-icon-search"
                  clearable></el-input>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="handleClose"
                   size="mini">{{$t('cancel')}}</el-button>
        <el-button type="primary"
                   size="mini"
                   @click.native="compareCode">{{$t('confirm')}}</el-button>
      </span>
    </el-dialog>
    <ExportOptionDialog :exportOptionDialogVisible="exportOptionDialogVisible"
                          :loading="exportGetAllDataLoading"
                          :pages="pageConfig.pages"
                          v-if="pageFromType !== 'reportLayoutGrid'"
                          @closeExportOptionDialog="closeExportOptionDialog"
                          @confirmExport="confirmExport"></ExportOptionDialog>
      <export-dialog
          :visible.sync="exportDialog"
          :loading="exportGetAllDataLoading"
          :pages="pageConfig.pages"
          @confirm="gridExport"/>
  </div>
</template>

<script>
import Vue from 'vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
//import { Page, Group, Sort, Reorder, ColumnChooser, Toolbar, Filter, Selection, DetailRow, Resize, Freeze, Aggregate, ColumnMenu, PdfExport, ExcelExport, GridPlugin, CommandColumn, Edit } from '@syncfusion/ej2-vue-grids'
import { defaultGadgetSettingList } from '@/utils/data-json'
import { grids } from 'ejs'
import formviewdialog from './components/form-view-dialog'
import drillDialog from './components/drill-dialog'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import { debounce, cloneDeep, uniqBy } from 'lodash'
import moment from 'moment'
import { getLodop } from '@/utils/LodopFuncs'
import BTable from '@/components/storybook/b-table'
import { exportCvs, exportExcel, exportPdf } from "@/utils/exportPdfCvs";
import { isHaveQuotationMarks } from "@/utils/common";
import crudPlusBtn from "@/components/gadget/crud-form-plus/crud-plus-btn.vue";
import ExportOptionDialog from '@/components/export-option-dialog/dialog.vue'
import exportDialog from '@/components/export-option-dialog/export-dialog.vue'
import vueQr from 'vue-qr'
export default {
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: { formviewdialog, Lastupdatetime, BTable, crudPlusBtn, drillDialog, ExportOptionDialog, exportDialog, vueQr,  model: () => import('@/components/gadget/query-model/query-model') },
  data () {
    return {
      search: '',
      multipleSelection: [],
      sumObj: {},
      sumObjFixed: {},
      currentTime: null,
      floatNum: 0,
      maxColItem: 0,
      gadgetSetting: {},
      AggColumn: [],
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      isGridInit: false,
      dataList: [],
      loading: false,
      heightoffset: 60,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'crudformplusgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'crudformplusgadget' }).gadgetSetting
        }
      },
      conditionFormat: [],
      footerTemp: function () {
        return {
          template: Vue.component('footerTemplate', {
            template: `<span>{{data.Custom}}</span>`,
            data () { return { data: {} } }
          })
        }
      },
      AverageTemp: function () {
        return {
          template: Vue.component('footerTemplate', {
            template: `<span>{{data.Custom}}</span>`,
            data () { return { data: {} } }
          })
        }
      },
      Min: function () {
        return {
          template: Vue.component('avgTemplate', {
            template: `<span>{{data.Min}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      Max: function () {
        return {
          template: Vue.component('avgTemplate', {
            template: `<span>{{data.Max}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      Count: function () {
        return {
          template: Vue.component('avgTemplate', {
            template: `<span>{{data.Count}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      CrudBtn: function () {
        return { template: CrudBtn }
      },
      toolbarItem: [], // 'ExcelExport'
      wrapSettings: { wrapMode: 'Both' },
      queryId: '',
      queryDrillthrough: {},
      queryDrillthroughList: [],
      selectFields: [],
      widgetName: '',
      formViewData: {
        isNew: true,
        formTitle: null,
        formCode: null,
        id: null,
        formKey: null,
        saveCondition: null
      },
      linkedDatasetList: [],

      toolbarEventList: [],
      columnEventList: [],
      formViewVisible: false,
      rowDataItem: {},
      queryShow: true,
      assignData: {},
      drillDialogVisible: false,
      queryData: {},
      dialogVisible: false,
      qrcontent: {
        code: '',
        text: ''
      },
      outboundCode: '',
      refreshNum: 0,
      toolbarResult: {},
      formatDataList: [],
      triggerBot:false,
      btnConditionList:[],
      exportOptionDialogVisible: false,
      exportDialog: false,
      exportGetAllDataLoading: false,
      toolBarExportType: null
    }
  },

  created () {
    // this.query()
    Vue['this_crud_form_plus_page_'] = this
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
  },
  mounted () {

  },
  computed: {
    comDataList () {
      var _self = this
      // return Array.isArray(_self.dataList) ? _self.dataList : []
      var retdata = _self.dataList
      return retdata
    },
    toolbarEventListPermisson () {
      let temp = []
      for (let i = 0; i < this.toolbarEventList.length; i++) {
        const element = this.toolbarEventList[i]
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        this[`${this.toolbarEventList[i].action}Loading`] = false
        if (this.$hasPermission(this.gadgetSetting.report.formList + ':' + element.action)) {
          // temp.push(element)
        }
      }
      temp = this.toolbarEventList// TODO
      return temp
    },
    comIsShowSummary () {
      return this.AggColumn.length !== 0
    },
    comColumns () {
      return this.gadgetSetting.report.columns.filter(v => v.visible)
    },
  },
  watch: {

  },
  methods: {
    getColumnWidth (columnName) {
      let maxLength = this.dataList.reduce((acc, row) => {
        const length = String(row[columnName]).length
        return length > acc ? length : acc
      }, 0)
      maxLength = columnName.length + 3 > maxLength ? columnName.length + 3 : maxLength
      return `${maxLength * 8 + 50}px`
    },
    getActionColumnWidth (arr) {
      let num = 0
      arr.map(item => {
        if (item.text) {
          num = num + item.text.length + 1
        }
        if (item.icon) {
          num = num + 3
        }
      })
      return `${(num * 15 + 30) < 220 ? 220 : num * 15 + 30}px`
    },
    sortChange ({ prop, order }) {
      if (order) {
        this.dataList = this.dataList.sort((a, b) => {
          const aStr = a[prop] ? String(a[prop]).toLowerCase() : ''
          const bStr = b[prop] ? String(b[prop]).toLowerCase() : ''
          let compareValue = aStr.localeCompare(bStr)
          return order === 'ascending' ? compareValue : -compareValue
        })
      } else {
        this.dataList = cloneDeep(this.dataListClone)
      }
    },
    customSort (a, b, filed) {
      const aStr = a[filed] ? a[filed].toLowerCase() : ''
      const bStr = b[filed] ? b[filed].toLowerCase() : ''
      return aStr.localeCompare(bStr)
    },
    searchTableData (val) {
      if (!Array.isArray(val)) return []
      return val.filter(data => {
        let str = ''
        Object.keys(data).map(item => {
          str = str + JSON.stringify(data[item])
        })
        return !this.search || str.toLowerCase().includes(this.search.toLowerCase())
      })
    },
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    actionHandler: debounce(function (data, row) {
      var _self = this
      _self.assignData = {}
      _self.rowDataItem = row
      if (row && _self.rowDataItem.column) delete _self.rowDataItem.column
      _self.formViewData = {
        formCode: data.formCode ? data.formCode : '',
        formKey: data.formKey ? data.formKey : '',
        dataFrom: data.dataFrom ? data.dataFrom : 'rowdata', // rowdata / api /review,
        action: data.action ? data.action : '',
        saveCondition: data.saveCondition ? data.saveCondition : null,
        actionConfig: data.actionConfig ? data.actionConfig : null
      }
      _self.assignData = data.assignData ? data.assignData : {}
      _self.queryData = data.queryData ? data.queryData : {}
      _self.triggerBot = data.triggerBot ? data.triggerBot: false
      if (data.action === 'rowEdit') {
        _self.formViewVisible = true
        this.$nextTick(() => {
          if (data.dataFrom === 'review') this.$refs['formView-dialog'].width = '80%'
          if(data.dialogWidth) this.$refs['formView-dialog'].width = data.dialogWidth
          this.$refs['formView-dialog'].visible = true
        })
      }
      if (data.action === 'rowInserOrEdit') {
        _self.formViewVisible = true
        this.$nextTick(() => {
          if (data.dataFrom === 'review') this.$refs['formView-dialog'].width = '80%'
          if(data.dialogWidth) this.$refs['formView-dialog'].width = data.dialogWidth
          this.$refs['formView-dialog'].visible = true
        })
      }
      if (data.action === 'rowdataview') {
        _self.formViewVisible = true
        this.$nextTick(() => {
          if (data.dataFrom === 'review') this.$refs['formView-dialog'].width = '80%'
          if(data.dialogWidth) this.$refs['formView-dialog'].width = data.dialogWidth
          this.$refs['formView-dialog'].visible = true
        })
      }
      // this.$refs['formView-dialog'].width = '90%'
      // assignDataText
      if (data.action === 'apiUpdate') {
        this.$confirm(data.assignDataText ? data.assignDataText : '确认操作', '提示', {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }).then(() => {
          _self.updateFormData()
        })
      }
      if (data.action === 'edit') {
        _self.commandClick('Edit', row)
      }
      if (data.action === 'delete') {
        this.deleteForm({ id: this.rowDataItem[this.formViewData.formKey] })
      }
      if (data.action === 'deleteMultiple') {
        this.deleteFormMultiple(data)
      }
      if (data.action === 'output') {
        data.printData.formCode = data.formCode ? data.formCode : null
        this.output(row, data.printData ? data.printData : {})
      }
      if (data.action === 'jumpLink') {
        this.$root.eventBus.$emit('close')
        this.$router.push(this.replaceString(data.linkAddress))
      }
      if (data.action === 'apiRequest') {
        this.apiRequest(data)
      }
      if (data.action === 'rowDialog') {
        _self.drillDialogVisible = true
        let tempData = {}
        tempData = this.queryDataParams(_self.queryData, _self.rowDataItem)
        this.$nextTick(() => {
          this.$refs['drill-dialog'].visible = true
          this.$refs['drill-dialog'].init(tempData)
        })
      }
      if (data.action === 'outview') {
        this.qrcontent.code = row[data.printData.data.code] ? row[data.printData.data.code] : ''
        this.qrcontent.text = row[data.printData.data.text] ? row[data.printData.data.text] + ' / ' + row['smatl_type'] + ' / ' + row['material_num'] : ''
        this.dialogVisible = true
      }

      if (data.action === 'BATCH_Request') {
        if (!this.multipleSelection.length) return false
        this.$confirm(data.api.confirmMsg ? data.api.confirmMsg : this.$t('prompt.confirm'), this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }).then(() => {
          let tempData = []
          for (let i = 0; i < this.multipleSelection.length; i++) {
            let batchKey = {}
            Object.keys(data.api.params).map(item => {
              const reg = /\{(.*?)\}/g;
              if (reg.test(data.api.params[item])) {
                batchKey[item] = this.replaceString(data.api.params[item], this.multipleSelection[i])
              } else {
                batchKey[item] = data.api.params[item]
              }
            })
            tempData.push(batchKey)
          }
          this.batchRequest(data, tempData)
        }).catch(() => {

        })
      }
      if (data.action === 'FormInsert') {
        this.formInsterApi(data)
      }
      if (data.action === 'BATCH_Request_FormInsert') {
        if (!this.multipleSelection.length) return false
        this.$confirm(data.api.confirmMsg ? data.api.confirmMsg : this.$t('prompt.confirm'), this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }).then(() => {          
          for (let i = 0; i < this.multipleSelection.length; i++) {
            let batchKey = {}
            Object.keys(data.api.params).map(item => {
              const reg = /\{(.*?)\}/g;
              if (reg.test(data.api.params[item])) {
                batchKey[item] = this.replaceString(data.api.params[item], this.multipleSelection[i])
              } else {
                batchKey[item] = data.api.params[item]
              }
            })
            this.formInsterApi({formCode: data.formCode, params: batchKey})
          }         
        }).catch(() => {

        })
      }
      if (data.action === 'FormUpdate') {
        this.formUpdateApi(data)
      }
      if (data.action === 'OpenLinkBtn') {
        _self.hyperLinkAction(data, _self.rowDataItem)
      }
      if (data.action === 'rowNewPage') {
        row.action = data.action ? data.action : '',
        row.saveCondition = data.saveCondition ? data.saveCondition : null,
        row.actionConfig = data.actionConfig ? data.actionConfig : null
        row.formCode = data.formCode ? data.formCode : null
        row.formKey = data.formKey ? data.formKey : null
        row.dataFrom = data.dataFrom ? data.dataFrom : 'rowdata'

        _self.btnConditionList.push({
            "opt": "===",
            "value": `${row[row.formKey]}`,
            "action": "disable",
            "column": "id"
          })
        _self.columnEventList.find(i =>i.action === 'rowNewPage' && i.formCode === row.formCode).condition = _self.btnConditionList
        _self.columnEventList = JSON.parse(JSON.stringify(_self.columnEventList))
        let routerJump = this.$router.resolve({ path: 'rowNewPage' })
        localStorage.setItem('rowData_outPage', JSON.stringify(row))
        window.open(routerJump.href, '_blank')
      }
    }, 1000, { 'leading': true, 'trailing': false }),
    queryDataParams (queryData, rowData) {
      let temp = {}
      temp.gadgetId = queryData.gadgetId
      let keyList = queryData.rowKey
      let drillThrough = null
      let filterList = []
      for (let index = 0; index < keyList.length; index++) {
        const ele = keyList[index]
        if (rowData[ele]) {
          filterList.push({
            key: `{` + ele + `}`,
            value: `'` + rowData[ele] + `'`
          })
        }
      }
      for (let i = 0; i < filterList.length; i++) {
        const element = filterList[i]
        drillThrough = queryData.filter.replaceAll(element.key, element.value)
      }
      temp.drillThrough = drillThrough
      return temp
    },
    formInsterApi (data) {
      var params = {
        formCode: data.formCode,
        dataContent: this.execObject(data.params),
        tenantCode: this.$store.state.user.tenantCode
      }
      this.$interface.reports.addOrUpdateFormDataApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.queryItem()
        this.$message.success(this.$t('success'))
      }).catch(() => {
      })
    },
    formUpdateApi (data) {
      var params = {
        formCode: data.formCode,
        id: this.rowDataItem[data.formIdKey], // ID form data Id
        dataContent: this.execObject(data.params),
        tenantCode: this.$store.state.user.tenantCode
      }
      this.$interface.reports.addOrUpdateFormDataApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.queryItem()
        this.$message.success(this.$t('success'))
      }).catch(() => {
      })
    },
    mappingFormInsert (data, type) {
      let params = {}
      let keyList = []
      keyList = Object.keys(data)
      for (let i = 0; i < keyList.length; i++) {
        const ele = keyList[i]
        params[ele] = this.rowDataItem[ele]
        if (type === 1) {
          if (ele === 'ticket_status_key') {
            params['ticket_status_key'] = data['ticket_status_key']
          }
        }
      }
      return params
    },
    output (row, printData) {
      if (printData.type === '2') {
        var LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'))
        LODOP.PRINT_INIT(`打印 - ${row[printData.data.text]}`)
        LODOP.NewPage()
        LODOP.SET_PREVIEW_WINDOW(1, 0, 0, 600, 600, `打印 - ${row[printData.data.text]}`)
        LODOP.SET_PRINT_PAGESIZE(1, 820, 290, '')
        LODOP.SET_PRINT_MODE('PRINT_NOCOLLATE', 1)
        LODOP.ADD_PRINT_BARCODE(4, 30, 100, 100, 'QRCode', `${row[printData.data.code]}`)
        LODOP.ADD_PRINT_TEXT(92, 30, 150, 23, `${row[printData.data.text]}`)
        LODOP.SET_PRINT_STYLEA(0, 'FontName', '微软雅黑')
        LODOP.SET_PRINT_STYLEA(0, 'FontSize', 10)
        LODOP.SET_PRINT_STYLEA(0, 'Bold', 1)
        LODOP.ADD_PRINT_BARCODE(4, 190, 100, 100, 'QRCode', `${row[printData.data.code]}`)
        LODOP.ADD_PRINT_TEXT(92, 190, 150, 23, `${row[printData.data.text]}`)
        LODOP.SET_PRINT_STYLEA(0, 'FontName', '微软雅黑')
        LODOP.SET_PRINT_STYLEA(0, 'FontSize', 10)
        LODOP.SET_PRINT_STYLEA(0, 'Bold', 1)
        //  LODOP.PRINT_DESIGN()
        LODOP.PREVIEW()
        // LODOP.PRINT()
      }
      if (printData.type === '3') {
        let temp = []
        printData.data.code.split('/').map(e => {
          let val = ''
          if (e === 'dateTimeNow') {
            val = moment().format('YYYY-MM-DD HH:mm:ss')
          } else {
            val = row[e] ? row[e] : '暂无信息'
          }
          val && temp.push(val)
        })
        var printVal = this._.uniq(temp).join('/')
        var LODOP1 = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'))
        LODOP1.PRINT_INIT(`打印 - ${row[printData.data.text]}`)
        LODOP1.NewPage()
        LODOP1.SET_PREVIEW_WINDOW(1, 0, 0, 600, 600, `打印 - ${row[printData.data.text]}`)
        LODOP1.SET_PRINT_PAGESIZE(1, 820, 290, '')
        LODOP1.SET_PRINT_MODE('PRINT_NOCOLLATE', 1)
        LODOP1.ADD_PRINT_BARCODE(4, 30, 100, 100, 'QRCode', `${printVal}`)
        LODOP1.ADD_PRINT_TEXT(92, 30, 150, 23, `${row[printData.data.text]}`)
        LODOP1.SET_PRINT_STYLEA(0, 'FontName', '微软雅黑')
        LODOP1.SET_PRINT_STYLEA(0, 'FontSize', 10)
        LODOP1.SET_PRINT_STYLEA(0, 'Bold', 1)
        LODOP1.ADD_PRINT_BARCODE(4, 190, 100, 100, 'QRCode', `${printVal}`)
        LODOP1.ADD_PRINT_TEXT(92, 190, 150, 23, `${row[printData.data.text]}`)
        LODOP1.SET_PRINT_STYLEA(0, 'FontName', '微软雅黑')
        LODOP1.SET_PRINT_STYLEA(0, 'FontSize', 10)
        LODOP1.SET_PRINT_STYLEA(0, 'Bold', 1)
        //  LODOP1.PRINT_DESIGN()
        LODOP1.PREVIEW()
        // LODOP1.PRINT()
      }
      if (printData.type === 'rowdata') {
        let routerJump = this.$router.resolve({ path: 'print' })
        row.formCode = printData.formCode ? printData.formCode : null
        row.dataFrom = printData.type
        row.currentPrintUser = this.$store.state.user.realName
        row.currentPrintTime = moment().format('YYYY-MM-DD HH:mm:ss')
        localStorage.setItem('rowData_print', JSON.stringify(row))
        window.open(routerJump.href, '_blank')
        //window.open(routerJump.href, '_blank')
      }
    },
    outputView () {
      this.dialogVisible = true
    },
    openedOut () {
      this.$nextTick(() => {
        this.$refs.codeinput.focus()
      })
    },
    handleClose () {
      this.dialogVisible = false
      this.qrcontent = {
        code: '',
        text: ''
      }
      this.outboundCode = ''
    },
    compareCode: debounce(function () {
      if (!this.outboundCode) {
        return this.$message.error('请输入物料编码或扫描物料二维码!')
      }
      if (this.outboundCode && ((this.outboundCode === this.qrcontent.code) || (this.outboundCode.split('/')[0] === this.qrcontent.code))) {
        let data = {
          'api': {
            'url': '/web/ddj/ticket/update/status',
            'method': 'POST',
            'params': {
              'id': '',
              'confirm_type': '3'
            }
          },
          'formKey': 'id'
        }
        this.apiRequest(data)
        this.handleClose()
        this.$message('确认出库')
      } else {
        // this.outboundCode = ''
        this.$message('扫描结果 和当前领料单物料不匹配！')
      }
    }, 1000, { 'leading': true, 'trailing': false }),
    async batchRequest (data = {}, items = []) {
      try {
        let tempMsg = data.api.successMsg ? data.api.successMsg : ''
        data.loading = true
        const { customRequest } = this.$interface
        let { method, url } = data.api || {}
        url = this.replaceString(url)
        const { data: response } = await customRequest(method, url, items)
        if (response.code !== 0) {
          throw response.msg
        }
        this.queryItem()
        this.$message.success(tempMsg ? tempMsg : response.msg)
        // window.location.reload()
      } catch (error) {

      } finally {
        data.loading = false
      }
    },
    apiRequest (data) {
      let params = {}
      params = this.execObject(data.api.params)
      let url = this.replaceString(data.api.url)
      this.$interface.customRequest(data.api.method, url, params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.queryItem()
        return this.$message.success(res.msg)
      })
    },
    commandClick (type, row) {
      var _self = this
      if (type === 'Edit') {
        const rowData = {
          formCode: _self.gadgetSetting.report.formList,
          id: row[_self.gadgetSetting.report.formData]
        }
        this.openDialog(rowData)
      }
    },
    allowAction (data) {
      this.allowdialogVisible = true
      this.$nextTick(() => {

      })
    },
    openDialog (row) {
      if (row) {
        if (!row.formCode || !row.id) return this.$message.error('Please select formList and formData in config and click Apply')
        this.formViewData = {
          isNew: false,
          formTitle: '', // this.$route.query.formTitle
          formCode: row.formCode,
          id: row.id
        }
      } else {
        if (!this.gadgetSetting.report.formList) return this.$message.error('Please select formList in config and click Apply')
        this.formViewData = { isNew: true, formCode: this.gadgetSetting.report.formList, formTitle: '' }
      }
      this.$nextTick(() => {
        // this.$refs.formViewDialog.visible = true
      })
    },
    deleteFormMultiple (data) {
      if (!this.multipleSelection.length) return false
      this.$confirm('Are you sure to delete?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(async () => {
        const { deleteFormMultiple } = this.$interface.reports
        const params = this.multipleSelection.map(item => {
          return item[data.formKey]
        })
        await deleteFormMultiple(params)
        this.$message({
          type: 'success',
          message: 'Successfully deleted!'
        })
        this.query()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Deletion canceled'
        })
      })
    },
    deleteForm (row) {
      if (!row.id) return this.$message.error('Please select formList and formData in config and click Apply')
      this.$confirm(this.$t('custom.delete'), this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        const params = { id: row.id }
        this.$interface.reports.deleteFormDataApi(params).then(({ data: res }) => {
          if (res.code !== 0) {
            this.loading = false
            return this.$message.error(res.msg)
          }
          this.$message({
            type: 'success',
            message: this.$t('deletesuccess')
          })
          this.queryItem()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('cancelDelete')
        })
      })
    },
    hyperLinkAction (actionData, rowData) {
      let pattern = actionData.linkAction.linkKey
      pattern = pattern.replace(/\{[\w\s]+\}/g, val => {
        // eslint-disable-next-line
        return val.replace(/[\{\}]/g, '')
      })
      let url = rowData[pattern] === null ? '' : rowData[pattern]
      if (!url) {
        return this.$message.error(actionData.linkAction.errMsg)
      } else {
        if (actionData.linkAction.isNewPage) {
          window.open(url, '_blank')
        }
      }
    },
    sortComparer: function (reference, comparer) {
      if (reference === 0 && this.isNull(comparer)) {
        return 1
      }
      if (reference < comparer) {
        return -1
      }
      if (reference > comparer) {
        return 1
      }
      return 0
    },
    isNull (value) {
      if (!value && typeof value !== 'undefined' && value !== 0) {
        return true
      } else {
        return false
      }
    },
    customSumFn: function (data, col) {
      let countLength = 0
      let floatNum = 0
      let num = 0
      for (let index = 0; index < this.dataList.length; index++) {
        let item = this.dataList[index]
        let data = getObject(col.field, item)
        if (!data) continue
        let numData = Number(data)
        countLength += numData
      }
      if (!Number.isInteger(countLength)) { num = countLength.toString().split('.')[1].length }
      if (num < 3) floatNum = num
      else floatNum = 2
      return this.toDecimal(countLength, floatNum)
    },
    toDecimal (x, m) {
      var val = Number(x)
      if (!isNaN(parseFloat(val))) {
        val = val.toFixed(m)
      }
      return val
    },
    customAggregateFn: function (data, col) {
      let count = getObject('count', data)
      let Aggregate = 0
      for (let index = 0; index < this.dataList.length; index++) {
        let item = this.dataList[index]
        let data = getObject(col.field, item)
        if (!data) continue
        let numData = Number(data)
        Aggregate += numData
      }
      let point = 2
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        let item = this.gadgetSetting.report.columns[index]
        if (col.field === item.field) {
          point = item.decimalPoint
          break
        }
      }
      // return Aggregate / count
      return this.fomatFloat(Aggregate / count, point)
    },
    fomatFloat (src, pos) {
      return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos)
    },
    returntempate (type) {
      if (type === 'Sum') {
        return this.Sum
      } else if (type === 'Average') {
        return this.Average
      } else if (type === 'Min') {
        return this.Min
      } else if (type === 'Max') {
        return this.Max
      } else if (type === 'Count') {
        return this.Count
      }
    },
    extractColumn () {
      this.maxColItem = 0
      let parentArr = []
      for (let i = 0; i < 5; i++) {
        let itemArr = []
        for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
          let item = this.gadgetSetting.report.columns[index]
          if (item.type === 'number' && item.aggregates.length > 0) {
            this.sumObj[item.field] = item.aggregates
            if (item.aggregates.includes('Average')) this.sumObjFixed[item.field] = item.decimalPoint
            if (this.maxColItem < item.aggregates.length) this.maxColItem = item.aggregates.length
            if (item.aggregates[i]) {
              itemArr.push({
                value: item.aggregates[i],
                field: item.field
              })
            }
          }
        }
        if (itemArr.length > 0) parentArr.push(itemArr)
      }
      this.AggColumn = parentArr
    },
    rowDataBound (args) {
      args.row.childNodes.forEach(item => {
        if (!this.gadgetSetting.report.fontsize) {
          this.gadgetSetting.report.fontsize = 14
        }
        item.style.fontSize = this.gadgetSetting.report.fontsize + 'px'
        item.style.lineHeight = this.gadgetSetting.report.fontsize + 'px'
        if (item.dataset.bgc) {
          // args.row.style.backgroundColor = item.dataset.bgc
          args.row.childNodes.forEach((ii, index) => {
            if (!ii.style.color) {
              if (index !== args.row.childNodes.length - 1) {
                ii.style.backgroundColor = item.dataset.bgc
              }
            }
          })
        }
        if (item.dataset.color) {
          args.row.childNodes.forEach(ii => {
            if (!ii.style.color) {
              ii.style.color = item.dataset.color
            }
          })
        }
      })
    },
    customiseCell (args) {
      try {
        var arr = this.conditionFormat
        var column = args.column.field
        let res = arr.filter(item => {
          if (item.dataForm.filters.rules.length !== 0) {
            return item.dataForm.filters.rules[0].key === column
          }
        })
        if (args.data) {
          res.forEach(it => {
            if (it) {
              let str = ''
              it.dataForm.filters.rules.forEach(ii => {
                // eslint-disable-next-line
                var val = args.data[ii.key].toString()
                if (ii.opt === '==' || ii.opt === '!=') {
                  if (!str) {
                    str += `("${(val).toString()}"  ${ii.opt}   "${(ii.value).toString()}")`
                  } else {
                    if (it.dataForm.filters.condition === 'and') {
                      str += `&& ("${(val).toString()}"  ${ii.opt}   "${(ii.value).toString()}")`
                    } else {
                      str += `|| ("${(val).toString()}"   ${ii.opt}   "${(ii.value).toString()}")`
                    }
                  }
                } else {
                  if (!str) {
                    str += (Number(val) + ii.opt + Number(ii.value))
                  } else {
                    if (it.dataForm.filters.condition === 'and') {
                      str += `&& (${Number(val)}   ${ii.opt}   ${Number(ii.value)})`
                    } else {
                      str += `|| (${Number(val)}   ${ii.opt}   ${Number(ii.value)})`
                    }
                  }
                }
              })
              // eslint-disable-next-line
              let res1 = eval(`${str}`)
              if (res1) {
                if (it.entireRow === 'row') {
                  args.cell.dataset.bgc = it.backgroundColor
                  args.cell.dataset.color = it.textColor
                } else {
                  args.cell.style.color = it.textColor ? it.textColor : '#000000'
                  args.cell.style.backgroundColor = it.backgroundColor
                }
              }
            }
          })
        }
      } catch (error) {

      }
    },
    dataBound (args) {
      if (!this.isGridInit) {
        this.isGridInit = true
        this.applyGadgetSetting()
      }
    },
    load (item) {
      this.grid = this.$refs.datagrid
      this.gadgetHeight = this.pageFrom === 'reportLayout' ? ((this.gadgetInfo.h * 20) - 15) : ((this.gadgetInfo.h * 23) - 15)
    },
    async queryItem () {
      this.refreshNum++
      if (this.refreshNum >= 20) {
        this.refreshNum = 0
        this.$store.state.contentIsNeedRefresh = true
        this.$store.state.app.contentIsNeedRefreshCache = true
        this.$nextTick(() => {
          this.$store.state.contentIsNeedRefresh = false
        })
      } else {
        this.queryShow = false
        // destoryDeep(this.$refs.datagrid)
        this.query()
      }
    },
    async destroyDeep (vnode) {
      let vnodes
      if (vnode.$children) {
        vnodes = vnode.$children
        for (const vn of vnodes) {
          this.destroyDeep(vn)
        }
      }

      vnode.$destroy()
      // vnode.$el.parentNode.removeChild(vnode.$el)
    },
    applyGadgetSetting () {
      let columnsList = []
      let isAutofit = false
      // process link column
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        const element = this.gadgetSetting.report.columns[index]
        // add template and drillThrough
        columnsList.push(element.field)
        if (this.gadgetSetting.report.columns[0] && !this.gadgetSetting.report.columns[0].width) {
          isAutofit = true
        }
        // datetime format bugfix
        if (this.gadgetSetting.report.columns[index].type === 'datetime') {
          this.gadgetSetting.report.columns[index].type = 'text'
        }
        if (this.gadgetSetting.report.columns[index].type === 'date') {
          this.gadgetSetting.report.columns[index].type = 'text'
        }
      }
      // this.gadgetSetting.report.columns.push(this.CrudBtn)
      // this.gadgetSetting.report.columns.pop()
      if (isAutofit) {
        columnsList = Object.keys(this.dataList[0])
        if(this.grid.ej2Instances) this.grid.ej2Instances.autoFitColumns(columnsList)
      }
      // this.grid.ej2Instances.setProperties(this.gadgetSetting.report)
      this.$forceUpdate()
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    queryModelPreview () {
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = newH * 20 - this.heightoffset - 35 + 32
      this.gadgetWidth = newWPx
    },
    replaceString (str, row) {
      const reg = /\{(.*?)\}/g;
      if (reg.test(str)) {
        const regex = /\{(.*?)\}/;
        let field = str.match(regex);
        if (row) {
          if (!row[field[1]]) {
            // this.$message.error(`${field[1]} field not found`)
            return str
          }
          str = str.replace(reg, row[field[1]])
        } else {
          if (!this.rowDataItem[field[1]]) {
            // this.$message.error(`${field[1]} field not found`)
            return str
          }
          str = str.replace(reg, this.rowDataItem[field[1]])
        }
      }
      return str
    },
    replaceDataMapping (json1, json2) {
      for (var key in json2) {
        var value = json2[key];
        if (typeof json2[key] === "object") {
          json2[key] = this.replaceDataMapping(json1, json2[key])
        } else {
          while (typeof value === "string"&&value.indexOf("{") > -1) {
            var oldValue = value.substring(value.indexOf("{") + 1, value.indexOf("}"))
            var newValue = this.replaceString(json1[oldValue]) ? this.replaceString(json1[oldValue]):''
            if(typeof newValue === 'object'){
              value = newValue
            }else{
              value = value.replace("{" + oldValue + "}", newValue)
            }
          }
          json2[key] = value
        }
      }
      return json2
    },
    execObject (objStr) {
      let obj = {}
      let rowData = {}
      let templateObj = {
        now: moment.tz(moment().utc(), this.$store.state.user.timezoneId).format(),
        now_date: moment.tz(moment().utc(), this.$store.state.user.timezoneId).format('YYYY-MM-DD'),
        now_time: moment.tz(moment().utc(), this.$store.state.user.timezoneId).format('HH:mm:ss'),
        current_user_id: this.$store.state.user.id,
        current_user_name: this.$store.state.user.realName,
        now_utc: moment().utc().format(),
        now_date_utc: moment().utc().format('YYYY-MM-DD'),
        now_time_utc: moment().utc().format('HH:mm:ss')
      }
      if (this.rowDataItem) {
        rowData = this.rowDataItem
      }
      obj = this.replaceDataMapping(Object.assign(templateObj, rowData), objStr)
      return obj
    },
    updateFormData () {
      let batchKey = {}
      if (this.assignData) {
        batchKey = this.execObject(this.assignData)
      }
      let params = {
        data: batchKey,
        filter: {
          id: this.rowDataItem[this.formViewData.formKey]
        },
        triggerBot:this.triggerBot
      }
      this.$interface.reports.updateFormDataFromKey(params).then(({ data: res }) => {
        if (res.code !== 0) {
          this.loading = false
          return this.$message.error(res.msg)
        }
        this.loading = false
        this.$message.success(this.$t('prompt.success'))
        this.queryItem()
      }).catch(() => {

      })
    },
    async query (e) {
      let isPaging = false
      try {
        if (this.isQueryModel && this.isQueryModel()) {
          isPaging = this.dataInfo.gadgetSetting.report.allowPaging
        } else {
          const { gadgetSetting } = await this.getWidgetInfo(this.id)
          isPaging = gadgetSetting.report.allowPaging
        }
      } catch (error) {

      }
      var _self = this
      // this.dataList = []
      _self.gadgetSetting = {}
      _self.dataList = []
      _self._.merge(_self.gadgetSetting, _self.queryModelDefaultSetting.dataInfo.gadgetSetting)
      if (e !== 'auto') {
        this.loading = true
      }
      var obj = JSON.parse(JSON.stringify(this.slicer))
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      if (!param.pageId) {
        param.type = 'widget'
      }
      _self.queryDrillthrough = {}
      _self.queryDrillthroughList = []
      _self.selectFields = []
      if(this.$route.path !== '/publicReportPdf'&& isPaging) {
        param.current = this.pageConfig.current
        param.size = this.pageConfig.pageSize
      }
      this.$interface.reports.getReportDataInfo(param)
        .then(({ data: res }) => {
          this.currentTime = new Date()
          _self.verifyHasData(res)
          try {
            _self.$parent.$parent.$parent.$parent.$parent.$parent.selectFields = res.selectFields
          } catch (error) {

          }
          _self.heightoffset = 5
          _self.gadgetHeight = this.pageFrom === 'reportLayout' ? ((_self.gadgetInfo.h * 20) - _self.heightoffset - 15) : ((_self.gadgetInfo.h * 23) - _self.heightoffset - 15)
          if (res.config) {
            _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
            _self.toolbarItem = _self.gadgetSetting.report.allowGrouping ? _self.gadgetSetting.report.toolbar : []
            _self.setfieldsFormat(res.selectFields)
            if (_self.gadgetSetting.report && _self.gadgetSetting.report.toolbarEventList) _self.toolbarEventList = _self.gadgetSetting.report.toolbarEventList
            if (_self.gadgetSetting.report && _self.gadgetSetting.report.columnEventList) _self.columnEventList = _self.gadgetSetting.report.columnEventList
          }
          if (res.name) {
            _self.widgetName = res.name
          } else if (this.wName) {
            _self.widgetName = this.wName
          } else {
            _self.widgetName = _self.gadgetSetting.headerTitle
          }
          _self.isGridInit = false
          // process data
          if (res.data) {
            try {
              if(res.data.records) {
                this.pageConfig.total = res.data.total
                res.data = res.data.records
              }
              this.formatDataList = this.formatData(JSON.parse(JSON.stringify(res.data)), res.selectFields, 'gridgadget')
            } catch (error) {
              
            }
            res.data = JSON.parse(JSON.stringify(res.data))
            _self.dataList = JSON.parse(JSON.stringify(res.data))
            _self.dataListClone = cloneDeep(res.data)
            _self.setColumsFormat(res.selectFields)
            this.extractColumn()
            _self.conditionFormat = res.conditionFormat
            _self.linkedDatasetList = res.datasetSync
          }

          _self.isGridInit = false
          _self.selectFields = res.selectFields
        })
        .catch(() => {
          if (this.wName) {
            this.widgetName = this.wName
          }
          this.loading = false
        }).finally(() => {
          this.autoRefreshQuery(e)
          this.queryShow = true
          this.$forceUpdate()
          this.updateGadgetLoadingStatus(!this.loading)
        })
    },
    destroyed () {
      delete Vue['this_crud_form_plus_page_']
    },
    remove () {
      this.close()
      if (this.drop.parentNode) {
        this.drop.parentNode.removeChild(this.drop)
      }
    },
    setfieldsFormat (fieldsList) {
      this.gadgetSetting.report.columns.forEach(item => {
        var res = fieldsList.find(i => {
          return i.bind === item.field
        })
        // if (!res) {
        //   res = fieldsList.find(e => e['dataType'] === 'dimension')
        // }
        // if (!res) {
        //   res = fieldsList.find(e => e['alias'] === 'dimension1')
        // }
        item.fieldsNewFormat = res && res.fieldsNewFormat
        item.fieldsFormat = res && res.fieldsFormat
        item.isNewPage = res && res.isNewPage
        item.showbymonday = res && res.showbymonday
        item.fieldsList = fieldsList
      })
    },
    setColumsFormat (fieldsList) {
      try {
        this.gadgetSetting.report.columns.forEach(item => {
          let fieldItemIndex = fieldsList.findIndex(e => e['bind'] === item['field'])
          // fieldItemIndex === -1 && (fieldItemIndex = fieldsList.findIndex(e => e['dataType'] === 'dimension'))
          // fieldItemIndex === -1 && (fieldItemIndex = fieldsList.findIndex(e => e['alias'] === 'dimension1'))
          if (fieldItemIndex === -1) throw new Error('No Format')
          if (item.type === 'number' && fieldsList[fieldItemIndex].businessType === 'number') {
            item.templateName = 'formatNumber'
          } else {
            let templateName = this.findTemplateName(fieldsList[fieldItemIndex].fieldsFormat, fieldsList[fieldItemIndex].businessType)
            item.templateName = templateName
          }
        })
      } catch (error) { }
    },
    getSummaries (param) {
      let result = []
      const { columns } = param;
      if (!columns.length) return
      columns.forEach((column, index) => {
        const { property } = column;
        if (this.sumObj[property]) {
          const value = this.getResultValue(property, this.dataList, this.sumObj[property], this.sumObjFixed[property]);
          result[index] = this.getJsx(value);
        } else {
          result[index] = '';
        }
      })
      return result;
    },
    handleTableExport (key) {      
      if ((key === 'Excel Export' || key === 'CSV Export') && this.gadgetSetting.report.showExportOption) {
        this.toolBarExportType = key
        this.exportDialog = true
        return false;
      }
      switch (key) {
        case 'PDF Export':
          if (this.gadgetSetting.report.showExportOption) {
            this.exportOptionDialogVisible = true
          } else {
            exportPdf(this.formatDataList, this.selectFields)
          }
          break
        case 'Excel Export':
          this.formatDataList.forEach(item => {
            for (let key in item) {
              if (item[key] && item[key].toString().includes('<a')) {
                item[key] = item[key].replace(/[a-zA-z]+:\/\/[\S]*/, val => {
                  if (val[val.length - 1] === '"') {
                    val = val.slice(0, val.length - 1)
                  }
                  // eslint-disable-next-line
                  let temp = encodeURIComponent(val) + '\"'
                  return temp
                })
              }
            }
          })
          exportExcel(this.formatDataList, this.selectFields)
          break
        case 'CSV Export':
          exportCvs(this.formatDataList, this.selectFields)
          break
      }
    },
    closeExportOptionDialog () {
      this.exportOptionDialogVisible = false
    },
    async gridExport (exportType) {
      const data = await this.getGridAllData(exportType)
      switch (this.toolBarExportType) {
        case 'Excel Export':
          data.forEach(item => {
            for (const key in item) {
              if (item[key] && item[key].toString().includes('<a')) {
                item[key] = item[key].replace(/[a-zA-z]+:\/\/[\S]*/, val => {
                  if (val[val.length - 1] === '"') {
                    val = val.slice(0, val.length - 1)
                  }
                  return encodeURIComponent(val) + '\"'
                })
              }
            }
          })
          exportExcel(data, this.selectFields)
          break
        case 'CSV Export':
          exportCvs(data, this.selectFields)
          break
      }
      this.exportDialog = false
    },
    async confirmExport (options) {
      const data = await this.getGridAllData(options.exportData)
      exportPdf(data, this.selectFields, options)
      this.exportOptionDialogVisible = false
    },
    async getGridAllData (exportType) {
      const getAllData = exportType === 'All' && this.gadgetSetting.report.allowPaging
      if (exportType === 'Current') return this.formatDataList;
      this.exportGetAllDataLoading = true
      let obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (let key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      let param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      if (!getAllData) {
        param.current = Number(exportType)
        param.size = this.pageConfig.pageSize
      }
      const getDataFunction = this.autoFull ? this.$interface.reports.getReportGridDataInfo : this.$interface.reports.getReportDataInfo
      const { data: { data: allData, selectFields } } = await getDataFunction(param)
      this.exportGetAllDataLoading = false
      return this.formatData(JSON.parse(JSON.stringify(param.current ? allData.records : allData)), selectFields, 'gridgadget')
    },
    tableCellClick (rowData, columnData) {
      for (var key in rowData) {
        if (rowData[key] && rowData[key].toString().includes("'") && (!rowData[key].toString().includes("''"))) {
          rowData[key] = rowData[key].toString().replace("'", "''")
        }
      }

      let column = this.selectFields.find(ele => ele.alias === columnData.label)
      if (this.selectFields.some(i => i.dataType === 'measure')) {
        if (!column.dataType) {
          return false
        }
      }
      if (!this.selectFields.some(i => i.dataType === 'dimension')) {
        if (!this.selectFields.some(i => i.dataType === 'measure')) {
          return false
        } else {
          this.queryId = this.selectFields.find(item => item.alias === columnData.label) ? this.selectFields.find(item => item.alias === columnData.label).queryId : ''
          return this.findOriginData('')
        }
      }
      if (column) {
        if (column.businessType === 'hyperlinks') {
          return false
        }
      }
      try {
        if (column.dataType === 'dimension') {
          return false
        }
      } catch (error) {

      }
      if (!rowData[columnData.label]) {
        return
      }

      var tempAlias = ''
      var tempData = ''
      var tempList = []
      var alias = ''
      var pointx = ''
      if (this.queryDrillthroughList && this.queryDrillthroughList.length > 0) {
        let dimensionList = this.selectFields.filter(e => e.dataType === 'dimension')
        dimensionList = uniqBy(dimensionList, 'alias')
        let params = {}
        if (dimensionList.length > 1) {
          params.name = rowData[column.alias]
          params.seriesName = column.alias
          params.selectObj = rowData
          this.setDrillThroughInfoMoreDimension(params)
          return
        }
      } else {
        this.queryId = this.selectFields.find(item => item.alias === columnData.label) ? this.selectFields.find(item => item.alias === columnData.label).queryId : ''
        this.queryDrillthrough = this.selectFields.find(i => i.queryId === this.queryId)
        if (this.queryDrillthrough && this.queryDrillthrough.alias) {
          tempAlias = rowData[this.queryDrillthrough.alias]
          if (!tempAlias && tempAlias !== false && tempAlias !== 0 && tempAlias !== '') {
            alias = 'dimension1'
            if (rowData['dimension1']) {
              tempAlias = rowData['dimension1']
            }
          } else {
            alias = this.queryDrillthrough.alias
          }
          try {
            var fx1 = this.queryDrillthrough.fieldFx
          } catch (error) {

          }
          if (this.queryDrillthrough.dbType === 'datetime' && tempAlias) {
            tempData = this.dateTimeTypeDrillthroughGrid(this.queryDrillthrough, fx1 || this.queryDrillthrough.field, tempAlias)
          } else {
            if (this.queryDrillthrough.dbType === 'date' && tempAlias) {
              tempData = this.dateTypeDrillthroughGrid(this.queryDrillthrough, fx1 || this.queryDrillthrough.field, tempAlias)
            } else {
              pointx = rowData[alias]
              if (!pointx && pointx !== false && pointx !== 0 && pointx !== '') {
                pointx = ' is null'
              } else {
                let ifHaveQuotationMarks = typeof (pointx) !== 'boolean' ? isHaveQuotationMarks(pointx) : false
                pointx = ifHaveQuotationMarks ? '=' + pointx : "= '" + pointx + "'"
              }
              if (fx1) {
                tempData = (fx1 || '') + pointx
              } else {
                tempData = '"' + ((this.queryDrillthrough.field) ? (this.queryDrillthrough.field) : '') + '"' + pointx
              }
            }
          }
        }
      }

      if (tempList && tempList.length > 0) {
        for (let i = 0; i < tempList.length; i++) {
          if (i === tempList.length - 1) {
            tempData += tempList[i].item
          } else {
            tempData += tempList[i].item + ' and '
          }
        }
      }
      this.queryId = this.selectFields.find(item => item.alias === columnData.label) ? this.selectFields.find(item => item.alias === columnData.label).queryId : ''
      if (this.queryId) {
        let data = ''
        data = tempData
        this.findOriginData(data)
      }
    },
    tableCellClassName ({ row, column }) {
      try {
        if (this.isShowCursor) {
          if (column.label !== 'dimension1') {
            let res = this.selectFields.find(i => {
              return i.alias === column.label
            })
            if (res.dataType) {
              if (res.dataType !== 'dimension') {
                if (typeof row[column.label] === 'boolean') {
                  return 'cursor-pointer'
                } else if (Number(row[column.label]) !== 0) {
                  return 'cursor-pointer'
                }
              }
            }
          }
        }
      } catch (error) {

      }
    },
    getTextAlign (align = 'left', display = 'block') {
      if (display === 'flex') {
        return {
          'left': 'flex-start',
          'center': 'center',
          'right': 'flex-end'
        }[align.toLowerCase()]
      }
      return ['left', 'center', 'right'].includes(align.toLowerCase()) ? align.toLowerCase() : align
    },
    getResultValue (property, data, keyArr = [], Fixed = 0) {
      let resultObj = {}
      let sum = data.reduce((c, r) => Number(c) + Number(r[property]), 0)
      let count = data.length
      let min = Math.min(...data.map(v => v[property]))
      let max = Math.max(...data.map(v => v[property]))
      keyArr.forEach(v => {
        switch (v) {
          case 'Sum':
            resultObj.Sum = sum
            break;
          case 'Average':
            resultObj.Average = (sum / count).toFixed(Fixed)
            break;
          case 'Min':
            resultObj.Min = min
            break;
          case 'Max':
            resultObj.Max = max
            break;
          case 'Count':
            resultObj.Count = count
            break;

          default:
            break;
        }
      })
      return resultObj
    },
    getJsx (val = {}) {
      let result = ""
      const keyArr = Object.keys(val)
      switch (keyArr.length) {
        case 1:
          result = (
            <div>
              <span>{keyArr[0]}:{val[keyArr[0]]}</span>
            </div>
          )
          break;
        case 2:
          result = (
            <div>
              <span>{keyArr[0]}:{val[keyArr[0]]}</span>
              <br />
              <span>{keyArr[1]}:{val[keyArr[1]]}</span>
            </div>
          )
          break;
        case 3:
          result = (
            <div>
              <span>{keyArr[0]}:{val[keyArr[0]]}</span>
              <br />
              <span>{keyArr[1]}:{val[keyArr[1]]}</span>
              <br />
              <span>{keyArr[2]}:{val[keyArr[2]]}</span>
            </div>
          )
          break;
        case 4:
          result = (
            <div>
              <span>{keyArr[0]}:{val[keyArr[0]]}</span>
              <br />
              <span>{keyArr[1]}:{val[keyArr[1]]}</span>
              <br />
              <span>{keyArr[2]}:{val[keyArr[2]]}</span>
              <br />
              <span>{keyArr[3]}:{val[keyArr[3]]}</span>
            </div>
          )
          break;
        case 5:
          result = (
            <div>
              <span>{keyArr[0]}:{val[keyArr[0]]}</span>
              <br />
              <span>{keyArr[1]}:{val[keyArr[1]]}</span>
              <br />
              <span>{keyArr[2]}:{val[keyArr[2]]}</span>
              <br />
              <span>{keyArr[3]}:{val[keyArr[3]]}</span>
              <br />
              <span>{keyArr[4]}:{val[keyArr[4]]}</span>
            </div>
          )
          break;

        default:
          break;
      }
      return result
    },
  }
}
const CrudBtn = Vue.component(
  'crud-btn', {
  template: `<div style="display: flex;justify-content: start;">
      <el-button size="mini" plain v-for="(item,index) in columnEventListPermisson" :key="index" @click="actionHandler(item,$data.data)"
      :disabled="disabledColumn(item,$data.data)"  :icon="item.icon" v-show="hideColumn(item,$data.data)" :type="item.type">{{item.text}}</el-button>
    </div>`,
  data () {
    return {
      columnEventList: Vue['this_crud_form_plus_page_'].columnEventList,
      formCode: Vue['this_crud_form_plus_page_'].gadgetSetting.report.formList
    }
  },
  computed: {
    columnEventListPermisson () {
      let temp = []
      for (let i = 0; i < this.columnEventList.length; i++) {
        const element = this.columnEventList[i]
        if (this.$hasPermission(this.formCode + ':' + element.action)) {
          // temp.push(element)
        }
      }
      temp = this.columnEventList
      return temp
    }
  },
  methods: {
    actionHandler (e, row) {
      Vue['this_crud_form_plus_page_'].actionHandler(e, row)
    },
    disabledColumn (item, row) {
      let temp = false
      if (item.condition && item.condition.column) {
        if (item.condition.action === 'disable') {
          temp = this.appendFunc(item, row)
        }
      }
      return temp
    },
    hideColumn (item, row) {
      let temp = true
      if (item.condition && item.condition.column) {
        if (item.condition.action === 'hide') {
          temp = !this.appendFunc(item, row)
        }
      }
      return temp
    },
    appendFunc (item, row) {
      // !==
      if (item.condition.opt === '!==') {
        if (row[item.condition.column] !== item.condition.value) {
          return true
        }
      }
      // ===
      if (item.condition.opt === '===') {
        if (row[item.condition.column] === item.condition.value) {
          return true
        }
      }
      // in & List value
      if (item.condition.opt === 'in' && Array.isArray(item.condition.value)) {
        let temp = false
        for (let i = 0; i < item.condition.value.length; i++) {
          const element = item.condition.value[i]
          if (row[item.condition.column] === element) {
            temp = true
            break
          }
        }
        return temp
      }
      // not null
      if (item.condition.opt === 'notnull') {
        if (row && row[item.condition.column]) {
          return true
        }
      }
    }

  }
}
)
</script>
<style lang="scss" scoped>
.content-card {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 45%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.grid_gadget_tempalte ::v-deep.e-grid .e-summarycell {
  font-size: 13px;
  background-color: #f6f6f6;
  border-color: #e0e0e0;
  color: rgba(0, 0, 0, 0.54);
  font-weight: normal;
}
.el-card ::v-deep .el-card__body {
  height: 100%;
  padding: 0px !important;
  height: 100%;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}

.header {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
}

.e-grid ::v-deep .e-filter-popup {
  max-height: 300px !important;
  overflow-y: auto;
}

.e-grid ::v-deep .e-checkboxlist {
  height: auto !important;
  overflow-y: visible !important;
}
.grid_gadget_tempalte ::v-deep .showToobar .e-grid .e-toolbar {
  display: none;
}
</style>
